import type { Router } from 'vue-router'
import { generateRouter } from '@/helper/router'
/**
 * 用户访问权限守卫
 */
import { usePermissionStore } from '@/store/modules/permissions'

const whiteList: string[] = ['/login', '/not-found']
export function gruadPerm(router: Router) {
  router.beforeEach(async (to, from, next) => {
    try {
      if (whiteList.includes(to.path)) {
        next()
        return
      }
      const permissionStore = usePermissionStore()
      if (!permissionStore.isGenerated) {
        await permissionStore.getPermission()
        await generateRouter(router).then(() => {
          next({ ...to, replace: true })
        })
      }
      else {
        next()
      }
    }
    catch (error) {
      console.error('权限守卫错误:', error)
    }
  })
}
